package com.example.cgpsys.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/server/{username}")
@Component
public class WebSocketController {

    public static Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username){
        sessionMap.put(username,session);
        JSONObject result = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        result.put("users",jsonArray);
        for (Object key:sessionMap.keySet()){
            JSONObject jsonObject= new JSONObject();
            jsonObject.put("username",key);
            jsonArray.add(jsonObject);
        }
        sendAllMessage(result.toJSONString());
    }

    @OnClose
    public void onClose(Session session, @PathParam("username") String username){
        sessionMap.remove(username);
    }

    @OnMessage
    public void onMessage(String message, Session session, @PathParam("username") String username){
        JSONObject object = (JSONObject) JSON.parse(message);
        String toUsername = object.getString("to");
        String text = object.getString("text");
        Session toSession = sessionMap.get(toUsername);
        if (toSession!=null){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("from",username);
            jsonObject.put("text",text);
            sendMessage(jsonObject.toJSONString(), toSession);
        }
    }

    @OnError
    public void onError(Session session, Throwable error){
        error.printStackTrace();
    }

    private void sendMessage(String message, Session toSession) {
        try {
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendAllMessage(String message){
        try {
            for (Session session:sessionMap.values()){
                session.getBasicRemote().sendText(message);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
